﻿using Abp.Dependency;
using Abp.Runtime;
using Abp.Runtime.Session;
using System;

namespace AbpProjectTemplate.Components.Configuration
{
    public class AutoSettingsTenantAndUserProvider : IAutoSettingsTenantAndUserProvider, ISingletonDependency
    {
        public const string TenantAndUserOverrideContextKey = "AbpProjectTemplate.Configuration.AutoSettingsTenantAndUserOverride";

        public int? TenantId => this.OverridedValue?.TentantId ?? this.AbpSession.TenantId;

        public long? UserId => this.OverridedValue?.UserId ?? this.AbpSession.UserId;

        protected IAbpSession AbpSession { get; }
        protected IAmbientScopeProvider<AutoSettingsTenantAndUserOverride> TenantAndUserOverrideProvider { get; }
        protected AutoSettingsTenantAndUserOverride OverridedValue => this.TenantAndUserOverrideProvider.GetValue(TenantAndUserOverrideContextKey);

        public AutoSettingsTenantAndUserProvider(
            IAmbientScopeProvider<AutoSettingsTenantAndUserOverride> tenantAndUserScopeProvider,
            IAbpSession abpSession
            )
        {
            this.TenantAndUserOverrideProvider = tenantAndUserScopeProvider;
            this.AbpSession = abpSession;
        }

        public IDisposable Use(long? userId, int? tenantId = null)
        {
            return this.TenantAndUserOverrideProvider.BeginScope(TenantAndUserOverrideContextKey,
                new AutoSettingsTenantAndUserOverride(tenantId, userId));
        }
    }
}
